Package org.javacommerce.google.ws

Source Code of org.javacommerce.google.ws.API

/**
*
*/
package org.javacommerce.google.ws;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.auth.BasicScheme;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.javacommerce.core.config.JavaCommerce;
import org.javacommerce.core.log.LogMessage;
import org.javacommerce.core.log.LogMessageFactory;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.SAXException;

import com.google.checkout.AddMerchantOrderNumber;
import com.google.checkout.AddTrackingData;
import com.google.checkout.ArchiveOrder;
import com.google.checkout.CancelOrder;
import com.google.checkout.ChargeOrder;
import com.google.checkout.CheckoutRedirect;
import com.google.checkout.CheckoutShoppingCart;
import com.google.checkout.DeliverOrder;
import com.google.checkout.Error;
import com.google.checkout.ProcessOrder;
import com.google.checkout.RefundOrder;
import com.google.checkout.RequestReceived;
import com.google.checkout.SendBuyerMessage;
import com.google.checkout.UnarchiveOrder;

/**
* Utility class for executing Google API calls.  Configuration is read from javacommerce.properties, located
* in the CLASSPATH.  Current values read are:
<table class="bodyTable">
<tr class="a">
<th>Field Name</th>
<th>Description</th>
<th>Required</th>
</tr>
<tr class="b">
<td>google.merchant.id</td>
<td>Merchant ID assigned by Google</td>
<td>Yes</td>
</tr>
<tr class="b">
<td>google.merchant.key</td>
<td>Merchant Key assigned by Google</td>
<td>Yes</td>
</tr>
<tr class="b">
<td>google.api.url</td>
<td>URL to send Google API calls to</td>
<td>No, defaults to Google Sandbox</td>
</tr>
</table>
* @author Michael Blanton (mike@mikeblanton.com)
*/
public class API {

  private static final String HMAC_SHA1 = "HmacSHA1";

  private static final String CONFIG_GOOGLE_MERCHANT_ID = "google.merchant.id";

  private static final String CONFIG_GOOGLE_MERCHANT_KEY = "google.merchant.key";

  private static final String CONFIG_GOOGLE_API_URL = "google.api.url";

  private static final String DEFAULT_GOOGLE_API_URL = "https://sandbox.google.com/cws/v2/Merchant";
 
  /**
   * Google Merchant ID read from the Configuration.
   */
  public static final String GOOGLE_MERCHANT_ID = JavaCommerce.getConfiguration().getString(CONFIG_GOOGLE_MERCHANT_ID);

  private static final Header HEADER_CONTENT_TYPE = new Header(
      "Content-Type", "application/xml");

  private static final Header HEADER_ACCEPT = new Header("Accept",
      "application/xml");

  private static final Log LOG = LogFactory.getLog(API.class);
  private static final LogMessage LOGM = LogMessageFactory.getInstance();

  private static String URL;
 
  public static APICredential DEFAULT_CREDENTIAL;
 
  static {
    DEFAULT_CREDENTIAL = new APICredential(JavaCommerce.getConfiguration().getString(
        CONFIG_GOOGLE_MERCHANT_ID), JavaCommerce
        .getConfiguration().getString(
            CONFIG_GOOGLE_MERCHANT_KEY));
  }

  /**
   * Base64 Encode the passed string.
   * @param _data
   * @return
   */
  public static final String base64Encode(String _data) {
    return new String(base64Encode(_data.getBytes()));
  }

  /**
   * Base64 Encode the passed byte array.
   * @param _data
   * @return
   */
  public static final byte[] base64Encode(byte[] _data) {
    return Base64.encodeBase64(_data);
  }

  /**
   * Generates the Cart Signature of the passed Checkout Shopping Cart Object.  This is then added to the <code>signature</code> parameter
   * of the Google Checkout Button.
   * @param _cart
   * @param _credential API Credentials to use when creating the header.
   * @return
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws MarshalException
   * @throws ValidationException
   * @see <a href="http://code.google.com/apis/checkout/developer/index.html#google_checkout_buttons">Google Checkout Buttons</a>
   */
  public static final String generateCartSignature(CheckoutShoppingCart _cart, APICredential _credential)
      throws NoSuchAlgorithmException, InvalidKeyException, MarshalException, ValidationException {
    long startTime = System.currentTimeMillis();
    byte[] bKey = _credential.getMerchantKey().getBytes();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_cart, writer);
    byte[] data = writer.toString().getBytes();
    Mac mac = Mac.getInstance(HMAC_SHA1);
    mac.init(new SecretKeySpec(bKey, HMAC_SHA1));

    // sign the shopping cart
    byte[] sig = mac.doFinal(data);
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.generateCartSignature", startTime, endTime);
    return new String(sig);
  }
 
  /**
   * Generates the Cart Signature of the passed Checkout Shopping Cart Object.  This is then added to the <code>signature</code> parameter
   * of the Google Checkout Button.
   * @param _cart
   * @return
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws MarshalException
   * @throws ValidationException
   * @see <a href="http://code.google.com/apis/checkout/developer/index.html#google_checkout_buttons">Google Checkout Buttons</a>
   */
  public static final String generateCartSignature(CheckoutShoppingCart _cart) throws InvalidKeyException, MarshalException, ValidationException, NoSuchAlgorithmException {
    return generateCartSignature(_cart, DEFAULT_CREDENTIAL);
  }

  /**
   * Posts the passed Checkout Shopping Cart Object to get a Checkout Redirect Object.  This is for the Alternative Technique for Posting Carts.
   * @param _cart
   * @return
   * @throws HttpException
   * @throws IOException
   * @throws ParserConfigurationException
   * @throws TransformerException
   * @throws SAXException
   * @throws MarshalException
   * @throws ValidationException
   * @throws JDOMException
   * @throws APIException
   * @see <a href="http://code.google.com/apis/checkout/developer/index.html#alternative_technique">Alternative Technique for Posting Carts</a>
   */
  public static final CheckoutRedirect postCheckoutShoppingCart(
      CheckoutShoppingCart _cart, APICredential _credentials) throws HttpException, IOException,
      ParserConfigurationException, TransformerException, SAXException,
      MarshalException, ValidationException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_cart, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.postCheckoutShippingCart", startTime, endTime);
    return (CheckoutRedirect) Unmarshaller.unmarshal(
        CheckoutRedirect.class, new StringReader(response));
  }
 
  /**
   * Posts the passed Checkout Shopping Cart Object to get a Checkout Redirect Object.  This is for the Alternative Technique for Posting Carts.
   * @param _cart
   * @return
   * @throws HttpException
   * @throws IOException
   * @throws ParserConfigurationException
   * @throws TransformerException
   * @throws SAXException
   * @throws MarshalException
   * @throws ValidationException
   * @throws JDOMException
   * @throws APIException
   * @see <a href="http://code.google.com/apis/checkout/developer/index.html#alternative_technique">Alternative Technique for Posting Carts</a>
   */
  public static final CheckoutRedirect postCheckoutShoppingCart(
      CheckoutShoppingCart _cart) throws HttpException, IOException,
      ParserConfigurationException, TransformerException, SAXException,
      MarshalException, ValidationException, JDOMException, APIException {
    return postCheckoutShoppingCart(_cart, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the ChargeOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived chargeOrder(ChargeOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.chargeOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the ChargeOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived chargeOrder(ChargeOrder _order)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    return chargeOrder(_order, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the RefundOrder API call.
   * @param _order
   * @param _credentials API credentials to use while posting the request
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived refundOrder(RefundOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.refundOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the RefundOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived refundOrder(RefundOrder _order)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    return refundOrder(_order, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the CancelOrder API call.
   * @param _order
   * @param _credentials API Credentials to use while posting the request.
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived cancelOrder(CancelOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.cancelOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the CancelOrder API call.
   * @param _order
   * @return
   * @throws APIException
   * @throws JDOMException
   * @throws IOException
   * @throws HttpException
   * @throws ValidationException
   * @throws MarshalException

   */
  public static final RequestReceived cancelOrder(CancelOrder _order) throws MarshalException, ValidationException, HttpException, IOException, JDOMException, APIException {
    return cancelOrder(_order, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the ProcessOrder API call.
   * @param _order
   * @param _credentials API credentials to use while posting the request
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived processOrder(ProcessOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.processOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the ProcessOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived processOrder(ProcessOrder _order)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    return processOrder(_order, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the DeliverOrder API call.
   * @param _order
   * @param _credential API Credentials to use while posting the request.
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived deliverOrder(DeliverOrder _order, APICredential _credential)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credential);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.deliverOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }

  /**
   * Executes the DeliverOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived deliverOrder(DeliverOrder _order)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    return deliverOrder(_order, DEFAULT_CREDENTIAL);
  }
  /**
   * Executes the AddTrackingData API call.
   * @param _data
   * @param _credential API Credentials to use when posting request.
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived addTrackingData(AddTrackingData _data, APICredential _credential)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_data, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credential);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.addTrackingData", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the AddTrackingData API call.
   * @param _data
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived addTrackingData(AddTrackingData _data) throws MarshalException, ValidationException, HttpException, IOException, JDOMException, APIException {
    return addTrackingData(_data, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the AddMerchantOrderNumber API call.
   * @param _data
   * @param _credential API Credentials to use when posting the request
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived addMerchantOrderNumber(
      AddMerchantOrderNumber _data,
      APICredential _credential) throws MarshalException,
      ValidationException, HttpException, IOException, JDOMException,
      APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_data, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credential);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.addMerchantOrderNumber", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the AddMerchantOrderNumber API call.
   * @param _data
   * @return
   * @throws APIException
   * @throws JDOMException
   * @throws IOException
   * @throws HttpException
   * @throws ValidationException
   * @throws MarshalException
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived addMerchantOrderNumber(AddMerchantOrderNumber _data) throws MarshalException, ValidationException, HttpException, IOException, JDOMException, APIException {
    return addMerchantOrderNumber(_data, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the SendBuyerMessage API call.
   * @param _message
   * @param _credentials API Credentials to use while posting the request.
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived sendBuyerMessage(
      SendBuyerMessage _message, APICredential _credentials) throws MarshalException,
      ValidationException, HttpException, IOException, JDOMException,
      APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_message, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.sendBuyerMessage", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the SendBuyerMessage API call.
   * @param _message
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived sendBuyerMessage(
      SendBuyerMessage _message) throws MarshalException,
      ValidationException, HttpException, IOException, JDOMException,
      APIException {
    return sendBuyerMessage(_message, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the ArchiveOrder API call.
   * @param _order
   * @param _credentials API Credentials to use when posting the request
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived archiveOrder(ArchiveOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.archiveOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the ArchiveOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived archiveOrder(ArchiveOrder _order) throws MarshalException, ValidationException, HttpException, IOException, JDOMException, APIException {
    return archiveOrder(_order, DEFAULT_CREDENTIAL);
  }

  /**
   * Executes the UnarchiveOrder API call.
   * @param _order
   * @param _credentials API Credentials to use while posting the request
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived unarchiveOrder(UnarchiveOrder _order, APICredential _credentials)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    long startTime = System.currentTimeMillis();
    StringWriter writer = new StringWriter();
    Marshaller.marshal(_order, writer);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Request: [" + writer.toString() + "]");
    }
    String response = postData(writer.toString(), _credentials);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Response: [" + response + "]");
    }
    long endTime = System.currentTimeMillis();
    LOGM.logSuccess("API.unarchiveOrder", startTime, endTime);
    return unmarshalRequestReceived(response);
  }
 
  /**
   * Executes the UnarchiveOrder API call.
   * @param _order
   * @return
   * @throws MarshalException
   * @throws ValidationException
   * @throws HttpException
   * @throws IOException
   * @throws JDOMException
   * @throws APIException
   */
  public static final RequestReceived unarchiveOrder(UnarchiveOrder _order)
      throws MarshalException, ValidationException, HttpException,
      IOException, JDOMException, APIException {
    return unarchiveOrder(_order, DEFAULT_CREDENTIAL);
  }

  private static RequestReceived unmarshalRequestReceived(String _xml)
      throws MarshalException, ValidationException {
    return (RequestReceived) Unmarshaller.unmarshal(RequestReceived.class,
        new StringReader(_xml));
  }

  private static final String postData(String _data, APICredential _credential) throws HttpException,
      IOException, MarshalException, ValidationException, JDOMException,
      APIException {
    HttpClient client = new HttpClient();
    PostMethod post = getPostMethod(_credential);
    post.setRequestEntity(new StringRequestEntity(_data, "application/xml",
        "UTF-8"));
    client.executeMethod(post);
    return validateResponse(post.getResponseBodyAsStream());
  }

  private static final String validateResponse(InputStream _input)
      throws JDOMException, IOException, MarshalException,
      ValidationException, APIException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new InputStreamReader(_input));
    if (doc.getRootElement().getName().equals("error")) {
      StringWriter writer = new StringWriter();
      XMLOutputter output = new XMLOutputter(Format.getCompactFormat());
      output.output(doc, writer);
      Error error = (Error) Unmarshaller.unmarshal(Error.class,
          new StringReader(writer.toString()));
      if (LOG.isDebugEnabled()) {
        LOG.debug("Error: [" + writer.toString() + "]");
      }
      throw new APIException("Error returned from Google.", error);
    }
    StringWriter writer = new StringWriter();
    XMLOutputter output = new XMLOutputter(Format.getCompactFormat());
    output.output(doc, writer);
    return writer.toString();
  }

  /**
   * Builds an Authorization Header based on the configured Username and Password.
   * @param _credential API Credentials to use when creating the header.
   * @return
   * @throws AuthenticationException
   */
  public static final String getAuthorizationHeader(APICredential _credential)
      throws AuthenticationException {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
        _credential.getMerchantId(), _credential.getMerchantKey());
    String header = BasicScheme.authenticate(credentials, "UTF-8");
    if (LOG.isDebugEnabled()) {
      LOG.debug("Authorization Header is [" + header + "]");
    }
    return header;
  }
 
  /**
   * Builds an Authorization Header based on the configured Username and Password.
   * @return
   * @throws AuthenticationException
   */
  public static final String getAuthorizationHeader() throws AuthenticationException {
    return getAuthorizationHeader(DEFAULT_CREDENTIAL);
  }

  private static final PostMethod getPostMethod(APICredential _credential)
      throws AuthenticationException {
    PostMethod post = new PostMethod(getURL());
    post.addRequestHeader(new Header("Authorization",
        getAuthorizationHeader(_credential)));
    post.addRequestHeader(HEADER_CONTENT_TYPE);
    post.addRequestHeader(HEADER_ACCEPT);
    return post;
  }

  private static final String getURL() {
    if (URL == null) {
      URL = new StringBuffer(JavaCommerce.getConfiguration().getString(
          CONFIG_GOOGLE_API_URL, DEFAULT_GOOGLE_API_URL)).append("/")
          .append(
              JavaCommerce.getConfiguration().getString(
                  CONFIG_GOOGLE_MERCHANT_ID)).append(
              "/request").toString();
      if (LOG.isDebugEnabled()) {
        LOG.debug("Using URL [" + URL + "]");
      }
    }
    return URL;
  }

}
TOP

Related Classes of org.javacommerce.google.ws.API

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.